from appserver import db_store
from models.entity.user import User
from models.entity.device import Device
from models.entity.facility import Facility
from models.entity.model_base import ModelBase

# 维护
class Maintenance(ModelBase):
    __tablename__ = "maintenance"
    __bind__ = "main"

    id = db_store.Column(db_store.Integer, primary_key=True, comment="主键")
    time = db_store.Column(db_store.DateTime,nullable=False,comment="维保时间")
    maintenance_type=db_store.Column(db_store.String(64),nullable=False,comment="维保类型")
    project_name=db_store.Column(db_store.String(64),nullable=False,comment="项目名称")
    facility_id=db_store.Column(db_store.Integer,comment="设施id")
    pump_house_location=db_store.Column(db_store.String(64),nullable=False,comment="泵房地址")
    device_id=db_store.Column(db_store.Integer,db_store.ForeignKey("devices.id"),nullable=False,comment="设备id")
    user_id=db_store.Column(db_store.Integer,db_store.ForeignKey("users.id"),nullable=False,comment="维修人员id")
    reason=db_store.Column(db_store.String(64),nullable=False,comment="故障原因")

    def __repr__(self):
        return "<Maintenance %s>" % self.time.strftime("%Y-%m-%d %H:%M:%S")
    
    def to_dict(self):
        rdic={}
        rdic["id"]=self.id
        rdic["time"]=self.time.strftime("%Y-%m-%d %H:%M")
        rdic["maintenance_type"]=self.maintenance_type
        rdic["project_name"]=self.project_name
        rdic["facility_id"]=self.facility_id
        the_facility=Facility().get_entity_by_id(self.facility_id)
        rdic["lat"]=the_facility.lat
        rdic["lng"]=the_facility.lng
        rdic["pump_house_location"]=self.pump_house_location
        the_device=Device.get_device_by_id(self.device_id)
        rdic["device_id"]=self.device_id
        rdic["device_name"]=the_device.name
        rdic["device_code"]=the_device.code
        rdic["user_id"]=self.user_id
        the_user=User.get_user_by_id(self.user_id)
        rdic["username"]=the_user.username
        rdic["reason"]=self.reason
        return rdic
    
    @staticmethod
    def get_maintenance_all_by_device_id(device_id):
        return Maintenance.query.filter_by(device_id=device_id).all()
